
//ARTISTS.JS
//shows the artists in the library
// Author: Wilco

function albumsPage() {}
albumsPage.prototype.constructor = albumsPage;
albumsPage.prototype =
{
    templateData: '',
    albumsJSON: '',
    albumsData: {},
    title: 'Albums',
	hooksData: null,
	listTmpl: null,
	searchInput: null,
	filters: '',
    loadPage: function()
    {
        this.onOutput = function(title,pageTemplate) { ProcessPageOutput(title,pageTemplate,'',true); }
        this.loadDefaults();
        //Load template data
        LoadFile(SkinDir + 'albums.html', this.onLoadTemplate.bind(this));
    },
    loadDefaults: function()
    {  
       //No Defaults
    },
    onLoadTemplate: function(response)
    {
        this.templateData = response;
        this.loadData();
    },
    loadData: function()
    {
		var url = ServiceDir;
		
		if (gPageData['albums']['year'])
		{	
            url = url + 'year/' + gPageData['albums']['year'] + '/';
            this.title = gPageData['albums']['year'];
			this.filters = this.filters + '&year=' + gPageData['albums']['year'];
        }
		if (gPageData['albums']['genre'])
		{
            url = url + 'genre/' + gPageData['albums']['genre'] + '/';
            this.title = gPageData['albums']['genre'];
			this.filters = this.filters + '&genre=' + gPageData['albums']['genre'];
        }
		if (gPageData['albums']['artist'])
		{
            url = url + 'artist/' + gPageData['albums']['artist'] + '/';
            this.title = gPageData['albums']['artist'];
			this.filters = this.filters + '&artist=' + gPageData['albums']['artist'];
        }
		
		if (this.filters.length > 0)
			this.filters = this.filters.substring(1);
			
        url = url + 'albums'; 
        LoadFile(url, this.onLoadData.bind(this));
    },
    onLoadData: function(response)
    {
       this.albumsJSON = response;
       this.generateOutput();
    },
    generateOutput: function()
    {
		
        try
        {    this.albumsData = eval("(" + this.albumsJSON + ")"); }
        catch (e)
        {    showError('Cannot understand service data: ' + this.albumsJSON); return; }        

		var tmpl = new Template();
		tmpl.load(this.templateData);
		
		this.listTmpl = tmpl.removeSubTemplate('list');
        this.listTmpl.addData({'filters': this.filters });
                
		this.albumsData.sort(function(a,b){ if (a.name<b.name) return -1; else if (a.name>b.name) return 1; else return 0;});
        this.onOutput(this.title,tmpl);
		
		//Hook events
		$('#SearchInput').bind('keyup',SearchUpdate);
		
		this.updateList(this.albumsData);
	},
    updateList: function(albums)
	{
		var tmpl = this.listTmpl.clone();
		var headertmpl = tmpl.removeSubTemplate('header');
		var itemtmpl = tmpl.removeSubTemplate('item');
        var items = [];
        var header;
        var prevHeader = '';
        var newtmpl = null;
		
		albums.sort(this.compareAlbums);
		for(var i=0;i<albums.length;i++)
		{
            if (albums.length > 50)
            {
                if (albums[i].name == null) continue; //FIXME: this shouldnt happen
                
				header = this.headerGroup(albums[i].name);
				if (header != prevHeader)
				{
                    newtmpl = headertmpl.clone();
                    newtmpl.addData({ 'group_title': header.toUpperCase() });
                    items.push(newtmpl);
                    prevHeader = header;
                }
            }
                
            newtmpl = itemtmpl.clone();
            newtmpl.addData({    album: albums[i].name,
								  index: i,
                            album_uri: encodeURIComponent(albums[i].name),
                        });
            items.push(newtmpl);
		}
		
		tmpl.addSubTemplate('item',items);
        document.getElementById('pagelist').innerHTML = tmpl.parse();
    },
	
	compareAlbums: function(albumA,albumB)
	{
		if (albumA.name == null) return -1;
		if (albumB.name == null) return -1;
		
		albumA = albumA.name.toLowerCase();
		albumA = albumA.substr(0);
		
		albumB = albumB.name.toLowerCase();
		albumB = albumB.substr(0);
		
		if (albumA < albumB) return -1;
		if (albumA > albumB) return 1;
		return 0;
	},
	headerGroup: function(album)
	{
		album = album.toLowerCase();
            
		if (album.length > 4 && album.substring(0,4) == 'the ')
			album = album.charCodeAt(4);
		else
			album = album.charCodeAt(0);
			
		if (album < 97) return ' ';			//ignore before A
		return String.fromCharCode(album);
	},
	runSearch: function(searchStr)
	{
		var albums = this.albumsData;
		albums = LocalSearch(albums,['name'],searchStr);
		this.updateList(albums);
	},
    onOutput: function(){},
}

function SearchUpdate(eventObj)
{
	var str = $('#SearchInput').val();
	gCurrentPage.runSearch(str);
}

function AlbumItemButton_Click(el,i)
{
	CreateMediaItemMenu(gCurrentPage.hooksData,gCurrentPage.albumsData[i]);
	ShowMenu();
}

gLastScriptLoaded = new albumsPage();
gScriptLoaded();